<?php
ob_start();
require_once('../inc/config.inc');
	//Connect to mysql server
	$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
	if(!$link) {
		die('Failed to connect to server: ' . mysql_error());
	}
	
	//Select database
	$db = mysql_select_db(DB_DATABASE);
	if(!$db) {
		die("Unable to select database");
	}
	if(isset($_GET['confirm_code'])){
		$key=$_GET['confirm_code'];
		$qry=mysql_query("SELECT * FROM `tw_temp_members` WHERE `confirm_code` ='".$key."'");
		if($qry){
		if(mysql_num_rows($qry)==1){
			$row=mysql_fetch_array($qry);
			$insert=mysql_query("INSERT INTO `users` VALUES(null,'".$row['firstname']."','".$row['lastname']."','".$row['email']."','".$row['password']."',null,null,null,null,null,'".$row['role']."')");
			if(!$insert){
				echo mysql_error();
				die();
			}
			$user_id=mysql_query("SELECT id FROM `users` order by id desc limit 1");
			$user_id_row = mysql_fetch_array($user_id);
			$role=$row['role'];
			if($role=="incubatee"){
			$insert2= mysql_query("INSERT INTO tw_incubatee VALUES('".$user_id_row['id']."',null)");
			}else{
				$insert2=mysql_query("INSERT INTO tw_mentor VALUES('".$user_id_row['id']."',null,null,null,null)");
			}
			if(!$insert2){
				echo mysql_error();
				die();
			}
			$delete=mysql_query("DELETE FROM `tw_temp_members` WHERE `confirm_code` = '".$key."' ");
			if($insert && $insert2 && $delete){
				header("Location: ../login.php?confirm=success");
			}
			else{
				echo "Error occured:1 " . mysql_error();
			}
		}
		else{
			echo "Your Link is invalid, please try again.";
		}
	}
	else{
		echo "NOT: " . mysql_error();
	}
	}
	else{
		header("Location: ../signup.php");
	}